<?php

namespace App\Http\Controllers\Api\Syj\Login;
use App\Common\Responses;
use App\Http\Controllers\Controller;
use App\Utils\Lib\Redis;
use App\Utils\Service\SMSSelection;
use App\Utils\Service\Syj\Login;
use App\Utils\Service\Syj\Token;
use App\Utils\Service\Syj\weChatService;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    /**
     * date 2023/04/18
     * user syj
     */
    private $token;//token验签

    public function __construct()
    {
        $this->token = new Token();
    }
    //用户选择第三方登录方式
    private const type="weChat";
    private const type1="QQ";
    //账户密码登录
    function Login(Request $request){
        $phone = $request->post('phone');//手机号
        $pwd = $request->post('pwd');//用户密码
        $captcha = $request->post('captcha');//验证码
        //账户密码登录
        if(!empty($phone) && !empty($pwd)){
            //dd($phone);
            $data = \App\Models\Syj\Broker\Login::findUser(['phone'=>$phone]);
            //dd($data);
            $pass = $data[0]['pwd'];
            //dd($pass);
            if($pwd != $pass){
                return Responses::error([],403,'密码不正确');
            }
            //推送公众号
            //weChatService::getInstance()->sendMessage($phone);
            return Responses::success([],200,'登录成功');
        }
        //手机号不为空验证码为空
        if(!empty($phone) && empty($captcha)){
            //判断手机号
            if(strlen($phone) != 11) return Responses::error(['error'=>'手机号必须为11位'],403,'手机号格式错误');
            //查询用户
            $user = \App\Models\Syj\Broker\Login::findUser(['phone'=>$phone]);
            //判断手机号是否存在
            if($user==[]){
                $param = [
                    'phone'=>$phone,
                    'pwd'=>'123456',
                    'add_time'=>time(),
                ];
                $data = \App\Models\Syj\Broker\Login::WechatRegister($param);
                $token = $this->token;
                $token = $token->encode($data);
                return Responses::success(['token'=>$token],200,'该账户未注册，自动注册账户成功');
            }
            //发送
            $way = SMSSelection::Selection(1)->makeReservation($phone);
            $res = array($way);
            return Responses::success($res,200,'短信发送成功');
        }
        //手机号不为空验证码不为空
        if(!empty($phone) && !empty($captcha)){
           $key = 'code'.$phone;
           $redis = Redis::createRedisObject();
           $redis->select(2);
           $code = $redis->GetRedis($key);
           if($captcha != $code)return Responses::error('',403,'验证码错误');
            //登录成功返回数据
            $token = $this->token;
            $token = $token->encode($phone);
            weChatService::getInstance()->sendMessage($phone);
            return Responses::success(['token'=>$token],200,'登录成功');
        }
        //第三方登录
        $login = new Login();
        //获取code
        $code = $request->post('code');
        //判断用户登录的方式
        if(!empty($code)){
            $WeChat = $login->ApiLogin(self::type);
            if(!$WeChat)return Responses::error([],403,'微信登录异常，请联系管理员');
            $WeChat->setCode($code);
            $data = $WeChat->Login();
            //授权失败返回信息
            if (isset($data['errmsg']))return Responses::error($data['errmsg']);
            $login=\App\Models\Syj\Broker\Login::FindUser('openid',$data['openid']);
            //获取微信用户是否已经注册
            if (!empty($login)){
                $u_id=$login->u_id;
                $data=\App\Models\Syj\Broker\Login::FindUser('id',$u_id);
                //登录成功返回持续化Token验证
                $token= $this->token;
                $token= $token->encode($data);
                //返回Token字符串
                $param=['token'=>$token];
                return Responses::success($param);
            }
            //通过微信注册用户
            $userInfo=[
                'nickname'=>"Wechat".rand(10,99),
                'pwd'=>md5("Wx12345".rand(10,99)),
                'wechat'=>'1',
                'created_at'=>date("Y-m-d H:i:s"),
                'updated_at'=>date("Y-m-d H:i:s")
            ];
            $data=\App\Models\Syj\Broker\Login::WechatRegister($userInfo);
            $token= $this->token;
            $token= $token->encode($data);
            return  Responses::success($token);
        }
        return Responses::error(['error'=>'登录形势错误']);
    }
}
